package com.clb.timetools;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class TimeToolsWindow extends JPanel {

    public TimeToolsWindow() {
        // 使用 BorderLayout 统一布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // ===== 顶部：当前时间 & 时间戳 显示区域 =====
        JPanel timeInfoPanel = new JPanel(new GridLayout(2, 1, 5, 5));

        JLabel currentTimeLabel = new JLabel("当前时间: ");
        JLabel currentTimestampLabel = new JLabel("当前时间戳 (ms): ");

        JButton copyTimeBtn = new JButton("复制");
        JButton copyTimestampBtn = new JButton("复制");
// 使用支持中文的字体
        copyTimeBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, 10));
        copyTimestampBtn.setFont(new Font(Font.DIALOG, Font.PLAIN, 10));

        Timer timer = new Timer(500, e -> {
            long timestamp = System.currentTimeMillis();
            Date date = new Date(timestamp);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            currentTimeLabel.setText("当前时间: " + sdf.format(date));
            currentTimestampLabel.setText("当前时间戳 (ms): " + timestamp);
        });
        timer.start();

        copyTimeBtn.addActionListener(e -> copyToClipboard(currentTimeLabel.getText().replace("当前时间: ", "")));
        copyTimestampBtn.addActionListener(e -> copyToClipboard(currentTimestampLabel.getText().replace("当前时间戳 (ms): ", "")));

        JPanel timeLine = new JPanel(new FlowLayout(FlowLayout.LEFT));
        timeLine.add(currentTimeLabel);
        timeLine.add(copyTimeBtn);

        JPanel timestampLine = new JPanel(new FlowLayout(FlowLayout.LEFT));
        timestampLine.add(currentTimestampLabel);
        timestampLine.add(copyTimestampBtn);

        timeInfoPanel.add(timeLine);
        timeInfoPanel.add(timestampLine);

        // ===== 中部：输入区域 =====
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
        inputPanel.setBorder(BorderFactory.createTitledBorder("输入"));

        JTextField inputField = new JTextField("请输入时间或时间戳", 20);
        inputField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (inputField.getText().equals("请输入时间或时间戳")) {
                    inputField.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (inputField.getText().isEmpty()) {
                    inputField.setText("请输入时间或时间戳");
                }
            }
        });

        JButton convertBtn = new JButton("自动识别并转换");

        // ===== 支持格式提示 =====
        JLabel hintLabel = new JLabel("<html><b>支持的时间格式：</b><br/>"
                + "• 标准格式：yyyy-MM-dd HH:mm:ss<br/>"
                + "• ISO8601：yyyy-MM-dd'T'HH:mm:ss.SSSZ<br/>"
                + "• RFC822：EEE, dd MMM yyyy HH:mm:ss Z<br/>"
                + "• 美国风格：MM/dd/yyyy hh:mm a<br/>"
                + "• 欧洲风格：dd/MM/yyyy HH:mm:ss<br/>"
                + "• 仅日期：yyyy-MM-dd<br/>"
                + "<b>支持的时间戳：</b><br/>"
                + "• 秒级时间戳（10位，如：1754596200）<br/>"
                + "• 毫秒级时间戳（13位，如：1754596200000）</html>");

        hintLabel.setFont(new Font("Arial", Font.PLAIN, 12));
        hintLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        inputPanel.add(new JLabel("输入时间或时间戳:"));
        inputPanel.add(inputField);
        inputPanel.add(hintLabel);
        inputPanel.add(Box.createVerticalStrut(5));
        inputPanel.add(convertBtn);

        // ===== 底部：结果区域 =====
        JTextArea resultArea = new JTextArea(5, 30);
        resultArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(resultArea);

        JButton copyResultBtn = new JButton("复制结果");
        copyResultBtn.setAlignmentX(Component.CENTER_ALIGNMENT);

        JPanel resultPanel = new JPanel();
        resultPanel.setLayout(new BoxLayout(resultPanel, BoxLayout.Y_AXIS));
        resultPanel.setBorder(BorderFactory.createTitledBorder("结果"));

        resultPanel.add(scrollPane);
        resultPanel.add(Box.createVerticalStrut(5));
        resultPanel.add(copyResultBtn);

        // ===== 将所有面板加入主窗口 =====
        add(timeInfoPanel, BorderLayout.NORTH);
        add(inputPanel, BorderLayout.CENTER);

        // 右侧结果面板（用 JSplitPane 可调整高度）
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false);
        splitPane.setTopComponent(inputPanel);
        splitPane.setBottomComponent(resultPanel);
        splitPane.setDividerLocation(250);
        splitPane.setResizeWeight(0.5);

        add(splitPane, BorderLayout.CENTER);

        // ===== 事件绑定 =====
        copyResultBtn.addActionListener(e -> {
            String text = resultArea.getText();
            if (!text.isEmpty()) {
                copyToClipboard(text);
            } else {
                JOptionPane.showMessageDialog(this, "结果为空，无法复制");
            }
        });

        convertBtn.addActionListener(e -> {
            String input = inputField.getText().trim();
            resultArea.setText("");

            if (isTimestamp(input)) {
                try {
                    long timestamp = Long.parseLong(input);

                    boolean isSeconds = false;
                    if (input.length() == 10) {
                        isSeconds = true;
                        timestamp *= 1000; // 秒转毫秒
                    } else if (input.length() == 13) {
                        // 毫秒直接使用
                    } else {
                        resultArea.setText("错误：不支持的时间戳长度，请输入 10 位（秒）或 13 位（毫秒）");
                        return;
                    }

                    Date date = new Date(timestamp);

                    // 使用你定义的所有格式模板
                    String[] formats = {
                            "yyyy-MM-dd HH:mm:ss",
                            "yyyy/MM/dd HH:mm:ss",
                            "yyyy-MM-dd'T'HH:mm:ss",
                            "yyyy-MM-dd'T'HH:mm:ss.SSS",
                            "yyyy-MM-dd'T'HH:mm:ssZ",
                            "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                            "EEE MMM dd yyyy HH:mm:ss",
                            "EEE, dd MMM yyyy HH:mm:ss Z",
                            "yyyy-MM-dd",
                            "MM/dd/yyyy HH:mm:ss",
                            "MM/dd/yyyy hh:mm a",
                            "dd/MM/yyyy HH:mm:ss"
                    };

                    StringBuilder output = new StringBuilder();
                    output.append("原始时间戳: ").append(input).append("\n");
                    output.append("类型: ").append(isSeconds ? "秒" : "毫秒").append("\n\n");

                    for (String format : formats) {
                        try {
                            SimpleDateFormat sdf = new SimpleDateFormat(format);
                            output.append(String.format("%-25s: %s%n", format, sdf.format(date)));
                        } catch (Exception ignored) {
                        }
                    }

                    resultArea.setText(output.toString());

                } catch (Exception ex) {
                    resultArea.setText("错误：无法识别的时间戳");
                }
            } else {
                Date parsedDate = parseDateString(input);
                if (parsedDate != null) {
                    long timestamp = parsedDate.getTime();
                    resultArea.setText("识别为时间字符串\n对应时间戳 (ms): " + timestamp);
                } else {
                    resultArea.setText("错误：无法识别输入内容，请输入合法时间或时间戳");
                }
            }
        });
    }

    private boolean isTimestamp(String input) {
        return Pattern.matches("^\\d+$", input);
    }

    private Date parseDateString(String input) {
        String[] formats = {
                "yyyy-MM-dd HH:mm:ss",
                "yyyy/MM/dd HH:mm:ss",
                "yyyy-MM-dd'T'HH:mm:ss",
                "yyyy-MM-dd'T'HH:mm:ss.SSS",
                "yyyy-MM-dd'T'HH:mm:ssZ",
                "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                "EEE MMM dd yyyy HH:mm:ss",
                "EEE, dd MMM yyyy HH:mm:ss Z",
                "yyyy-MM-dd",
                "MM/dd/yyyy HH:mm:ss",
                "MM/dd/yyyy hh:mm a",
                "dd/MM/yyyy HH:mm:ss"
        };

        for (String format : formats) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                return sdf.parse(input);
            } catch (Exception ignored) {
            }
        }

        return null;
    }

    private void copyToClipboard(String text) {
        StringSelection stringSelection = new StringSelection(text);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        JOptionPane.showMessageDialog(null, "已复制到剪贴板:\n" + text);
    }
}
